package com.cmc6.common.config;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Configuration
@Slf4j
public class RedissonClientConfig {

    @Value("${spring.redis.password:}")
    private String redisPassword;
    // 以 s结尾的，都是用逗号隔开的，所以这里在配置文件中，也是用逗号隔开的
    @Value("#{'${spring.redis.cluster.nodes:}'.split(',')}")
    private Set<String> nodeSet;

    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient() {

        Config config = new Config();

        List<String> nodeList = new ArrayList<>(nodeSet);
        String[] nodeArr = new String[nodeList.size()];
        String pre = "redis://";
        for (int i = 0; i < nodeList.size(); i++) {
            nodeArr[i] = pre + nodeList.get(i);
        }

        config.useClusterServers().setPassword(StrUtil.isBlank(redisPassword) ? null : redisPassword)
            .addNodeAddress(nodeArr).setMasterConnectionMinimumIdleSize(10).setSlaveConnectionMinimumIdleSize(10);

        log.info("Redisson 启动");
        return Redisson.create(config);
    }
}
